package com.yeping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeping.constants.SystemConstants;
import com.yeping.domain.ResponseResult;
import com.yeping.domain.dto.AddArticleDto;
import com.yeping.domain.entity.*;
import com.yeping.domain.vo.*;
import com.yeping.mapper.ArticalMapper;
import com.yeping.service.*;
import com.yeping.utils.BeanCopyUtils;
import com.yeping.utils.RedisCache;
import com.yeping.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.yeping.constants.SystemConstants.ARTICLE_STATUS_NORMAL;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticalMapper, Article> implements ArticalService {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private UserService userService;

    @Autowired
    private TagService tagService;

    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章,非草稿
        queryWrapper.eq(Article::getStatus,ARTICLE_STATUS_NORMAL);
        //按浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多查询十条
        Page<Article> page = new Page<>(1,10);
        page(page,queryWrapper);
        List<Article> articles = page.getRecords();

        //bean拷贝
//        List<HotArticleVo> articleVos = new ArrayList<>();
//        for (Article article : articles) {
//            HotArticleVo vo = new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            articleVos.add(vo);
//        }
        List<HotArticleVo> hotArticleVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);
        return ResponseResult.okResult(hotArticleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId,String title,String isForum) {
        //查询条件
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper();
        //如果有categoryId 查询时要和传入时相同
        wrapper.eq(Objects.nonNull(categoryId) && categoryId > 0,Article::getCategoryId,categoryId);
        //状态是正式发布的
        wrapper.eq(Article::getStatus,ARTICLE_STATUS_NORMAL);
        wrapper.eq(Objects.nonNull(isForum),Article::getIsForum,isForum);
        wrapper.like(Objects.nonNull(title),Article::getTitle,title);
        //对isTop进行降序
        wrapper.orderByDesc(Article::getIsTop);
        //分页查询
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,wrapper);

        //查询categoryName
        List<Article> articles = page.getRecords();
        /**
         * for循环查询
         */
        for (Article article : articles){
            if (Objects.nonNull(article.getCategoryId())){
                Category category = categoryService.getById(article.getCategoryId());
                article.setCategoryName(category.getName());
            }

        }

        /**
         * stream流
         */
//        articles = articles.stream()
//                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
//                .collect(Collectors.toList());

        //封装查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos, page.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticalDetail(Long id) {
        //根据ID获取文章
        Article article = getById(id);
        //从redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());
        //转换成Vo
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        //根据分类id查询分类名
        Category category = categoryService.getById(article.getCategoryId());
        if (category != null){
            articleDetailVo.setCategoryName(category.getName());
        }

        //封装响应返回
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        redisCache.incrementCacheMapValue("article:viewCount",String.valueOf(id),1);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult add(AddArticleDto articleDto) {
        //这里需要原子性
        //添加 博客
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        article.setUserId(SecurityUtils.getUserId());
        save(article);
        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());
        //添加 帖子和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult articleAll(String isForum,Long categoryId,String title) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Article::getIsForum, isForum);
        queryWrapper.like(Objects.nonNull(title),Article::getSummary,title);
        queryWrapper.eq(Article::getStatus, ARTICLE_STATUS_NORMAL);
        queryWrapper.eq(Article::getDelFlag, ARTICLE_STATUS_NORMAL);
        //如果有categoryId 查询时要和传入时相同
        queryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0,Article::getCategoryId,categoryId);
        List<Article> list = this.list(queryWrapper);
        List<ArticleAllVo> articleAllVos = BeanCopyUtils.copyBeanList(list, ArticleAllVo.class);
        for (ArticleAllVo vo : articleAllVos){
            User user = userService.getById(vo.getUserId());
            vo.setAvatar(user.getAvatar());
            vo.setNickName(user.getNickName());
        }
        return ResponseResult.okResult(articleAllVos);
    }

    @Override
    public ResponseResult seacherArtical(String keyword) {
        Article[] articles = getBaseMapper().seacherArticle(keyword);
        return ResponseResult.okResult(articles);
    }

    @Override
    public ResponseResult updateLike(Article article) {
        updateById(article);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateArticle(Article article) {
        article.setUserId(SecurityUtils.getUserId());
        //updateById(article);
        saveOrUpdate(article);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteArticle(Long articleId) {
        removeById(articleId);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delBatchUser(List<Long> ids) {
        removeByIds(ids);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getTags(Long articleId) {
        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(ArticleTag::getArticleId,articleId);
        List<Tag> tags = articleTagService.list(queryWrapper).stream()
                .map(articleTag -> tagService.getById(articleTag.getTagId()))
                .collect(Collectors.toList());
        return ResponseResult.okResult(tags);
    }
}
